//
//  MainVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/7/23.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "MainVC.h"
#import "TimelyVC.h"
#import "RemindVC.h"
#import "Wphone.h"
#import "Config.h"
#import "RecentHistoryVC.h"
#import "ContactVC.h"
#import "DynamicVC.h"
#import "MBTUiColor.h"
#import "RunVC.h"
#import "SportVC.h"
#import "OneVC.h"
#import "DbManage.h"
#import "HttpTool.h"
#import "MJExtension.h"
#import "BindTool.h"
#import "TContact.h"
#import "NewContactDao.h"
#import "TCallKeyborad.h"
#import "RunSucessInfo.h"
#import "MarkInfo.h"
#import "InterceptInfo.h"
#import "ContactPersonInfo.h"
#import "ContactPersonO.h"
#import "NetTools.h"
static const CGFloat kDefaultPlaySoundInterval = 3.0;
@interface MainVC ()<TCallKeyboradDelegate>{
    TimelyVC* timely;
    NSString *phone_number;
}
@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@property (strong,nonatomic)TCallKeyborad *keyboard;
@end

@implementation MainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    phone_number=[BindTool share].bindInfo.phone_number;
    [NetTools share].isHaveInternet;
    [self initTabBarViewController];
    [self updateContactToServer];
     _keyboard = [TCallKeyborad headerView];
    _keyboard.hidden=YES;
    _keyboard.delegate=self;
    //[self.view addSubview:_keyboard];
    [self getAllMarkToServer];
    //[self insertIntercept];
    //重新再获取头像的时候
    [self getAllHeadPic];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refrshContact:) name:@"conatctState" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadMessageCount) name:@"setupUnreadMessageCount" object:nil];
}

-(void)refrshContact:(NSNotification*)sender{
    if (!timely.isReadContactScuess) {
        [self updateContactToServer];
        dispatch_async(dispatch_get_main_queue(), ^{//一定要在主线程中更新啊
            [timely refrshContact];
        });
    }
}

-(instancetype)init{
    if (self = [super init]) {
        NSLog(@"MBTMainVC init");
    }
    return self;
}
//- (TCallKeyborad *)keyboard
//{
//    if (!_keyboard) {
//        _keyboard = [TCallKeyborad headerView];
//        _keyboard.delegate = self;
//    }
//    return _keyboard;
//}
-(void)contactkeyBoard:(UIButton*)b{//键盘的操作
    [timely.history contactkeyBoard:b];
}

-(void)initTabBarViewController{
     NSLog(@"self.navigationItem %@",self.navigationItem);
    
    timely =[[TimelyVC alloc]init];
    SportVC* heath = [[SportVC alloc]init];//真是无语啊
    RemindVC* remind = [[RemindVC alloc]init];
    //Wphone* wphone = [[Wphone alloc]init];
    OneVC *wphone =[[OneVC alloc]init];
    
    timely.hidesBottomBarWhenPushed = YES;
    heath.hidesBottomBarWhenPushed = YES;
    remind.hidesBottomBarWhenPushed = YES;
    wphone.hidesBottomBarWhenPushed = YES;
    
    UIImage* img5 = [UIImage imageNamed:@"timely_rain_nor"];
    UIImage* img6 = [UIImage imageNamed:@"sport_nor"];
    UIImage* img7 = [UIImage imageNamed:@"remind_time_nor"];
    UIImage* img8 = [UIImage imageNamed:@"device_nor"];
    
    UIImage* img1 = [UIImage imageNamed:@"timely_rain_pre"];
    UIImage* img2 = [UIImage imageNamed:@"sport_pre"];
    UIImage* img3 = [UIImage imageNamed:@"remind_time_pre"];
    UIImage* img4 = [UIImage imageNamed:@"device_pre"];
    
    [self addViewController:timely WithTabTitle:MLString(@"及时雨")  image:img5 selectImage:img1];
    [self addViewController:heath WithTabTitle:MLString(@"运动健康") image:img6 selectImage:img2];
    [self addViewController:remind WithTabTitle:MLString(@"计划提醒") image:img7 selectImage:img3];
    [self addViewController:wphone WithTabTitle:MLString(@"Wphone") image:img8 selectImage:img4];
    
    NSMutableArray* arrControllers = [[NSMutableArray alloc]init];
    [arrControllers addObject:timely];
    [arrControllers addObject:heath];
    [arrControllers addObject:remind];
    [arrControllers addObject:wphone];
    self.viewControllers = arrControllers;
    self.selectedIndex = 0;
}


#pragma mark 添加4个按钮
-(void)addViewController:(UIViewController *)controller WithTabTitle:(NSString *)title image:(UIImage *)image selectImage:(UIImage *)selI{
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    selI = [selI imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    controller.tabBarItem = [[UITabBarItem alloc] initWithTitle:title image:image selectedImage:selI];
}
-(void)updateContactToServer{
    //把数据读出来上传给服务器
    NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];
    NSString *plistPath =[doc stringByAppendingPathComponent:@"contact.plist"];
    NSError *er=nil;
    NSString* content = [NSString stringWithContentsOfFile:plistPath encoding:NSUTF8StringEncoding error:&er];
    if (er) {
        NSLog(@"读取失败啊啊%@",er);
        content=@"";
        timely.isReadContactScuess=NO;
    }else{
        timely.isReadContactScuess=YES;
        NSLog(@"content============%@",content);
        NSLog(@"phone_number====%@",phone_number);
        NSDictionary *parameters =@{@"user_id":phone_number,@"data":content};
        NSString *url =[apiUrl stringByAppendingString:saveContact];
        [HttpTool Post:url parameters:parameters success:^(id responseObject) {
            NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"updateContactToServer----=== %@",str);
        } failure:^(NSError *error) {
            
        }];
    }
}

// app的统计未读消息数
-(void)setupUnreadMessageCount
{
    NSLog(@"setupUnreadMessageCount");
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    if (timely) {
        if (unreadCount > 0) {
            timely.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
        }else{
            timely.tabBarItem.badgeValue = nil;
        }
    }
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];//给app统计未读消息的个数
}
- (void)playSoundAndVibration{
    NSLog(@"setupUnreadMessageCount");
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}
-(void)setKeyBoardHidden:(BOOL)isHidden{
    NSLog(@"setKeyBoardHidden====s=a=s=");
    if (isHidden) {
        _keyboard.hidden=YES;
    }else{
        _keyboard.hidden=NO;
    }
}
//获取所有的mark然后删掉数据库在插入
-(void)getAllMarkToServer{
    NSString *url =[apiUrl stringByAppendingString:getAllMark];
    NSDictionary *pa =@{@"user_id":phone_number,@"page":@"",@"pageSize":@20};//有为空的时候
    [HttpTool GET:url WithHeader:NO parameters:pa success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"getAllMarkToServer====%@",str);
        RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status) {
            NSDictionary *data = success.data;
            NSArray *marks =[data objectForKey:@"marks"];
            NSMutableArray *marksInfo =[NSMutableArray array];
            for (NSDictionary *dic in marks) {
                MarkInfo *info =[[MarkInfo alloc]init];
                info.time=[dic objectForKey:@"time"];
                info.number =[dic objectForKey:@"number"];
                info.mark =[dic objectForKey:@"mark"];
                [marksInfo addObject:info];
            }
            [[DbManage shareDbManage] deleteMarkInfoAll];
            [[DbManage shareDbManage] insertMarkInfoArray:marksInfo];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)insertIntercept{
    InterceptInfo *call =[[InterceptInfo alloc]init];
    call.to=@"7313818859";
    call.from=@"18927482671";
    call.type=@"call";
    call.time=@"313818314915719193";
    call.mark=@"黑名单";
    call.isRead=@"NO";
    call.attribution=@"深圳";
    call.content=@"我是诈骗带您大大的";
    
    InterceptInfo *call1 =[[InterceptInfo alloc]init];
    call1.to=@"7313818859";
    call1.from=@"18927482671";
    call1.type=@"sms";
    call1.time=@"313818314915719193";
    call1.mark=@"黑名单";
    call1.isRead=@"NO";
    call1.attribution=@"深圳";
    call1.content=@"我是诈骗带您大大的";
    
    NSMutableArray *array =[NSMutableArray array];
    [array addObject:call];
    [array addObject:call1];
    [[DbManage shareDbManage]insertInterceptInfoArray:array];
}

-(void)getAllHeadPic{
    __weak typeof(self) weakSelf = self;
    NSString *users =@"";
    NSMutableArray *contactArray =[[DbManage shareDbManage] queryConatctArray];
    for (TContact *model in contactArray) {
        users =[[users stringByAppendingString:model.phone] stringByAppendingString:@","];
    }
    users =[users stringByAppendingString:phone_number];
    NSString *url =[apiUrl stringByAppendingString:getUsers];
    [HttpTool GET:url WithHeader:NO parameters:@{@"userids":users} success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        ContactPersonO *success =[ContactPersonO mj_objectWithKeyValues:responseObject];
        if (success.status) {
             NSLog(@"getAllHeadPic====jadodaldladladlall,laldlaldaldl%@",str);
            if (success.data.count!=0) {
            for (ContactPersonInfo *info in success.data) {
                if (info.head_pic!=nil) {
                    for (TContact *model in contactArray) {
                        if ([info.user_id isEqualToString:model.group]) {
                            model.group=info.head_pic;
                            break;
                        }
                    }
                }
            }
            }
            [[DbManage shareDbManage] deleteAllPersonInfo];
            [[DbManage shareDbManage] insertPersonInfoArray:success.data];
        }
    } failure:^(NSError *error) {
        //有很多解析的问题啊,我去了啊
    }];
}
@end
